using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using RAG.Application.Interfaces;
using RAG.Application.Dtos;

namespace RAG.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class KnowledgeBaseController : ControllerBase
{
    private readonly IAppKnowledgeBaseService _knowledgeBaseService;

    public KnowledgeBaseController(IAppKnowledgeBaseService knowledgeBaseService)
    {
        _knowledgeBaseService = knowledgeBaseService;
    }

    /// <summary>
    /// 创建知识库
    /// </summary>
    [HttpPost]
    public async Task<IActionResult> CreateKnowledgeBase([FromBody] CreateKnowledgeBaseDto dto)
    {
        try
        {
            var userIdClaim = User.FindFirst("sub")?.Value
                ?? User.FindFirst("user_id")?.Value
                ?? User.FindFirst("uid")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                return BadRequest(new { code = 400, message = "无法获取用户信息" });
            }

            dto.UserId = userId;
            var result = await _knowledgeBaseService.CreateKnowledgeBaseAsync(dto);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"创建知识库时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 获取知识库列表
    /// </summary>
    [HttpGet]
    public async Task<IActionResult> GetKnowledgeBases()
    {
        try
        {
            var userIdClaim = User.FindFirst("sub")?.Value
                ?? User.FindFirst("user_id")?.Value
                ?? User.FindFirst("uid")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                return BadRequest(new { code = 400, message = "无法获取用户信息" });
            }

            var result = await _knowledgeBaseService.GetKnowledgeBasesAsync(userId);
            return Ok(result);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"获取知识库列表时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 获取知识库详情
    /// </summary>
    [HttpGet("{knowledgeBaseId}")]
    public async Task<IActionResult> GetKnowledgeBase(Guid knowledgeBaseId)
    {
        try
        {
            var result = await _knowledgeBaseService.GetKnowledgeBaseAsync(knowledgeBaseId);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"获取知识库详情时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 更新知识库
    /// </summary>
    [HttpPut("{knowledgeBaseId}")]
    public async Task<IActionResult> UpdateKnowledgeBase(Guid knowledgeBaseId, [FromBody] UpdateKnowledgeBaseDto dto)
    {
        try
        {
            dto.KnowledgeBaseId = knowledgeBaseId;
            var result = await _knowledgeBaseService.UpdateKnowledgeBaseAsync(dto);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"更新知识库时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 删除知识库
    /// </summary>
    [HttpDelete("{knowledgeBaseId}")]
    public async Task<IActionResult> DeleteKnowledgeBase(Guid knowledgeBaseId)
    {
        try
        {
            var userIdClaim = User.FindFirst("sub")?.Value
                ?? User.FindFirst("user_id")?.Value
                ?? User.FindFirst("uid")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                return BadRequest(new { code = 400, message = "无法获取用户信息" });
            }

            var result = await _knowledgeBaseService.DeleteKnowledgeBaseAsync(knowledgeBaseId, userId);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"删除知识库时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 添加文档到知识库
    /// </summary>
    [HttpPost("{knowledgeBaseId}/documents/{documentId}")]
    public async Task<IActionResult> AddDocumentToKnowledgeBase(Guid knowledgeBaseId, Guid documentId)
    {
        try
        {
            var result = await _knowledgeBaseService.AddDocumentToKnowledgeBaseAsync(knowledgeBaseId, documentId);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"添加文档到知识库时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 从知识库移除文档
    /// </summary>
    [HttpDelete("{knowledgeBaseId}/documents/{documentId}")]
    public async Task<IActionResult> RemoveDocumentFromKnowledgeBase(Guid knowledgeBaseId, Guid documentId)
    {
        try
        {
            var result = await _knowledgeBaseService.RemoveDocumentFromKnowledgeBaseAsync(knowledgeBaseId, documentId);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"从知识库移除文档时发生错误: {ex.Message}" });
        }
    }
}
